package com.lazy.interceptor;

import com.lazy.constant.JwtClaimsConstant;
import com.lazy.context.BaseContext;
import com.lazy.properties.JwtProperties;
import com.lazy.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    // true 放行  ；  false 不通过
    @Autowired
    private JwtProperties jwtProperties;
    public boolean preHandle(HttpServletRequest request ,
                             HttpServletResponse response,
                             Object handler){




        //1.获取请求url    http://localhost:8080/login
        String url = request.getRequestURI();


        //2.判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if (url.contains("login")) {
            return true;
        }
        //3.获取请求头中的令牌（token）
        try {
//            String token = request.getHeader("token");
            String token = request.getHeader(jwtProperties.getStudentTokenName());
            System.out.println(jwtProperties.getStudentTokenName());
            log.info("从请求头中获取的令牌：{}",token);

//            // 打印所有请求头
//            Enumeration<String> headerNames = request.getHeaderNames();
//            while (headerNames.hasMoreElements()) {
//                String headerName = headerNames.nextElement();
//                String headerValue = request.getHeader(headerName);
//                System.out.println("请求头: " + headerName + " = " + headerValue);
//            }


            //4.判断令牌是否存在，如果不存在，返回错误结果（未登录）
            Claims claims = JwtUtil.parseJWT(jwtProperties.getStudentSecretKey(),token);
            Long studentId = Long.valueOf(claims.get(JwtClaimsConstant.STUDENT_ID).toString());

            BaseContext.setCurrentId(studentId);

            log.info("当前学生id = " + studentId);
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
